package com.jinhao.crowd.mvc.config;

import com.jinhao.crowd.entity.Admin;
import com.jinhao.crowd.entity.Role;
import com.jinhao.crowd.service.api.AdminService;
import com.jinhao.crowd.service.api.AuthService;
import com.jinhao.crowd.service.api.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created on 2021/10/3.
 *
 * @author Valar Morghulis
 */
@Component
public class CrowdUserDetailsService implements UserDetailsService {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthService authService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取admin对象
        Admin admin = adminService.getAdminByLoginAcct(username);

        //得到adminId,获取角色,权限信息
        Integer adminId = admin.getId();

        List<Role> roleList = roleService.getAssignedRoles(adminId);
        List<String> authNameList = authService.getAssignedAuthNameByAdminId(adminId);

        List<GrantedAuthority> authorities = new ArrayList<>();

        // 遍历roleList，将角色名称添加到authorities
        for (Role role : roleList) {
            String name = role.getName();
            String roleName = "ROLE_" + name;

            authorities.add(new SimpleGrantedAuthority(roleName));
        }

        // 遍历authNameList,将权限名添加到authorities
        for (String authName : authNameList) {
            authorities.add(new SimpleGrantedAuthority(authName));
        }

        return new SecurityAdmin(admin, authorities);
    }
}
